package cz.mpelant.calllog;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.provider.CallLog;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Calendar calendar = Calendar.getInstance(Locale.CHINA);

    private TextView callStartTimeActionTv;
    private TextView callStartTimeTv;
    private TextView callStartDateTv;
    private TextView callStartDateActionTv;
    private RadioGroup callTypeRg;
    private EditText phoneNumberEt;
    private EditText callDurationEt;
    private Button addCallLogBtn;

    @Override
    protected void onResume() {
        super.onResume();

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_CALL_LOG}, 1000);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        addCallLogBtn = findViewById(R.id.addCallLogBtn);
        callStartTimeTv = findViewById(R.id.callStartTimeTv);
        callStartTimeActionTv = findViewById(R.id.callStartTimeActionTv);
        callStartDateTv = findViewById(R.id.callStartDateTv);
        callStartDateActionTv = findViewById(R.id.callStartDateActionTv);
        callTypeRg = findViewById(R.id.callTypeRg);
        phoneNumberEt = findViewById(R.id.phoneNumberEt);
        callDurationEt = findViewById(R.id.callDurationEt);

        callStartTimeActionTv.setOnClickListener(this);
        callStartDateActionTv.setOnClickListener(this);
        addCallLogBtn.setOnClickListener(this);

        callStartDateTv.setText(calendar.get(Calendar.YEAR) + "年" + (calendar.get(Calendar.MONTH) + 1) + "月" + calendar.get(Calendar.DAY_OF_MONTH) + "日");
        callStartTimeTv.setText(calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE) + ":00");
    }

    private void insertCallLog(String number, Date callTime, int duration, int type, int isNew) {
        ContentValues values = new ContentValues();
        values.put(CallLog.Calls.NUMBER, number);
        values.put(CallLog.Calls.DATE, callTime.getTime());
        values.put(CallLog.Calls.DURATION, duration);
        values.put(CallLog.Calls.TYPE, type);
        values.put(CallLog.Calls.NEW, isNew);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_CALL_LOG}, 1000);
        }
        getContentResolver().insert(CallLog.Calls.CONTENT_URI, values);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.callStartDateActionTv:
                showDatePickerDialog(this, 4, callStartDateTv, calendar);
                break;
            case R.id.callStartTimeActionTv:
                showTimePickerDialog(this, 4, callStartTimeTv, calendar);
                break;
            case R.id.addCallLogBtn:
                try {
                    final String phone = phoneNumberEt.getText().toString();
                    final Date callTime = calendar.getTime();
                    final int duration = Integer.parseInt(callDurationEt.getText().toString());
                    final int callType = getCallType();

                    insertCallLog(phone, callTime, duration, callType, 1);
                    Toast.makeText(this, "通话记录插入成功", Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }

    private int getCallType() {
        for (int i = 0; i < callTypeRg.getChildCount(); i++) {
            RadioButton rb = (RadioButton) callTypeRg.getChildAt(i);
            if (rb.isChecked()) {
                int callType = CallLog.Calls.INCOMING_TYPE;
                switch (rb.getId()) {
                    case R.id.incomingRb:
                        callType = CallLog.Calls.INCOMING_TYPE;
                        break;
                    case R.id.outgoingRb:
                        callType = CallLog.Calls.OUTGOING_TYPE;
                        break;
                }
                return callType;
            }
        }
        return CallLog.Calls.MISSED_TYPE;
    }

    public static void showDatePickerDialog(Activity activity, int themeResId, final TextView tv, final Calendar calendar) {
        // 直接创建一个DatePickerDialog对话框实例，并将它显示出来
        new DatePickerDialog(activity, themeResId, new DatePickerDialog.OnDateSetListener() {
            // 绑定监听器(How the parent is notified that the date is set.)
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // 此处得到选择的时间，可以进行你想要的操作
                calendar.set(Calendar.YEAR, year);
                calendar.set(Calendar.MONTH, monthOfYear);
                calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

                tv.setText(year + "年" + (monthOfYear + 1) + "月" + dayOfMonth + "日");
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
    }

    public static void showTimePickerDialog(Activity activity, int themeResId, final TextView tv, final Calendar calendar) {
        // 直接创建一个DatePickerDialog对话框实例，并将它显示出来
        new TimePickerDialog(activity, themeResId, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
                calendar.set(Calendar.MINUTE, minute);
                calendar.set(Calendar.SECOND, 0);

                tv.setText(hourOfDay + ":" + minute + ":00");
            }
        }, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true).show();
    }

}